package cc.plumgo.j2me.utils;

import java.io.DataInputStream;
import java.io.InputStream;

public class TextLoader {
	public String readUnicode(String resource) {
		byte [] buffer = new byte[1024];
		String ret = null;
		InputStream is;
		try {
			is = getClass().getResourceAsStream(resource);
			is.read(buffer);
			is.close();
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < buffer.length;) {
				int k = buffer[i++];
				if (k < 0) k += 256;
				
				int l = buffer[i++];
				if (l < 0) l += 256;
				char c = (char)(k + (l << 8));
				sb.append(c);
			}
			ret = sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			is = null;
		}
		return ret;
	}
	
	public String readUTF8(String resource) {
		String ret = null;
		InputStream is = null;
		byte [] buffer = new byte[1024];
		try {
			is = getClass().getResourceAsStream(resource);
			is.read(buffer);
			is.close();
			ret = new String(buffer, "UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			is = null;
		}
		return ret;
	}
	
	public String readBigEndianUnicode(String resource) {
		String ret = null;
		char [] buffer = new char[1024];
		
		DataInputStream dis;
		try {
			dis = new DataInputStream(getClass().getResourceAsStream(resource));
			int counter = 0;
			dis.skip(2);
			char tmp;
			while(true) {
				tmp = dis.readChar();
				if (tmp == '$') break;
				buffer[counter ++] = tmp;
			}
			dis.close();
			ret = String.valueOf(buffer, 0, counter);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			dis = null;
		}
		return ret;
	}
}
